#include "dtu_at_command.h"
#include "dtu_log.h"
#include "dtu_memory.h"
#include "dtu_data_collect.h"
#include "dtu_config.h"
#include <ctype.h>
#include <stdarg.h>

/* 全局AT命令解析器 */
static at_cmd_parser_t g_at_parser = {0};

/* 内部函数声明 */
static at_cmd_item_t* find_command(const char* name);
static dtu_error_t parse_command_line(const char* command_line, char* name, size_t name_size,
                                      at_cmd_type_t* type, at_cmd_params_t* params);
static void free_command_list(void);

/* AT命令处理函数声明 */
at_result_t dtu_at_cmd_basic(at_cmd_type_t type, const at_cmd_params_t* params,
                             at_cmd_response_t* response, void* user_data);

/* 系统信息命令 */
at_result_t dtu_at_cmd_info(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_version(at_cmd_type_t type, const at_cmd_params_t* params,
                               at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_serial_number(at_cmd_type_t type, const at_cmd_params_t* params,
                                     at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_model(at_cmd_type_t type, const at_cmd_params_t* params,
                             at_cmd_response_t* response, void* user_data);

/* 系统控制命令 */
at_result_t dtu_at_cmd_reset(at_cmd_type_t type, const at_cmd_params_t* params,
                             at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_save(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_load(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_factory(at_cmd_type_t type, const at_cmd_params_t* params,
                               at_cmd_response_t* response, void* user_data);

/* 网络管理命令 */
at_result_t dtu_at_cmd_network(at_cmd_type_t type, const at_cmd_params_t* params,
                               at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_ethernet(at_cmd_type_t type, const at_cmd_params_t* params,
                                at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_wifi(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_lte(at_cmd_type_t type, const at_cmd_params_t* params,
                           at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_ping(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);

/* 串口管理命令 */
at_result_t dtu_at_cmd_serial(at_cmd_type_t type, const at_cmd_params_t* params,
                              at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_rs485(at_cmd_type_t type, const at_cmd_params_t* params,
                             at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_rs232(at_cmd_type_t type, const at_cmd_params_t* params,
                             at_cmd_response_t* response, void* user_data);

/* 数据采集命令 */
at_result_t dtu_at_cmd_collect(at_cmd_type_t type, const at_cmd_params_t* params,
                               at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_modbus(at_cmd_type_t type, const at_cmd_params_t* params,
                              at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_device(at_cmd_type_t type, const at_cmd_params_t* params,
                              at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_read(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_pollstr(at_cmd_type_t type, const at_cmd_params_t* params,
                               at_cmd_response_t* response, void* user_data);

/* 数据推送命令 */
at_result_t dtu_at_cmd_push(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_mqtt(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_http(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_tcp(at_cmd_type_t type, const at_cmd_params_t* params,
                           at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_udp(at_cmd_type_t type, const at_cmd_params_t* params,
                           at_cmd_response_t* response, void* user_data);

/* 系统状态命令 */
at_result_t dtu_at_cmd_status(at_cmd_type_t type, const at_cmd_params_t* params,
                              at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_log(at_cmd_type_t type, const at_cmd_params_t* params,
                           at_cmd_response_t* response, void* user_data);
at_result_t dtu_at_cmd_time(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data);

dtu_error_t dtu_at_init(void)
{
    if (g_at_parser.initialized) {
        return DTU_OK;
    }

    memset(&g_at_parser, 0, sizeof(at_cmd_parser_t));

    /* 初始化互斥锁 */
    if (pthread_mutex_init(&g_at_parser.mutex, NULL) != 0) {
        return DTU_ERROR;
    }

    g_at_parser.initialized = true;

    /* 注册标准AT命令 */
    dtu_at_register_command("", "Basic AT command", dtu_at_cmd_basic, NULL);

    /* 系统信息命令 */
    dtu_at_register_command("I", "Device information", dtu_at_cmd_info, NULL);
    dtu_at_register_command("VER", "Firmware version", dtu_at_cmd_version, NULL);
    dtu_at_register_command("SN", "Serial number", dtu_at_cmd_serial_number, NULL);
    dtu_at_register_command("MODEL", "Device model", dtu_at_cmd_model, NULL);

    /* 系统控制命令 */
    dtu_at_register_command("RST", "Reset device", dtu_at_cmd_reset, NULL);
    dtu_at_register_command("SAVE", "Save configuration", dtu_at_cmd_save, NULL);
    dtu_at_register_command("LOAD", "Load configuration", dtu_at_cmd_load, NULL);
    dtu_at_register_command("FACTORY", "Factory reset", dtu_at_cmd_factory, NULL);

    /* 网络管理命令 */
    dtu_at_register_command("NET", "Network management", dtu_at_cmd_network, NULL);
    dtu_at_register_command("ETH", "Ethernet configuration", dtu_at_cmd_ethernet, NULL);
    dtu_at_register_command("WIFI", "WiFi configuration", dtu_at_cmd_wifi, NULL);
    dtu_at_register_command("LTE", "4G/LTE configuration", dtu_at_cmd_lte, NULL);
    dtu_at_register_command("PING", "Network ping test", dtu_at_cmd_ping, NULL);

    /* 串口管理命令 */
    dtu_at_register_command("SERIAL", "Serial port management", dtu_at_cmd_serial, NULL);
    dtu_at_register_command("RS485", "RS485 configuration", dtu_at_cmd_rs485, NULL);
    dtu_at_register_command("RS232", "RS232 configuration", dtu_at_cmd_rs232, NULL);

    /* 数据采集命令 */
    dtu_at_register_command("COLLECT", "Data collection", dtu_at_cmd_collect, NULL);
    dtu_at_register_command("MODBUS", "Modbus configuration", dtu_at_cmd_modbus, NULL);
    dtu_at_register_command("DEVICE", "Device management", dtu_at_cmd_device, NULL);
    dtu_at_register_command("READ", "Read device data", dtu_at_cmd_read, NULL);
    dtu_at_register_command("POLLSTR", "Poll string configuration", dtu_at_cmd_pollstr, NULL);

    /* 数据推送命令 */
    dtu_at_register_command("PUSH", "Data push management", dtu_at_cmd_push, NULL);
    dtu_at_register_command("MQTT", "MQTT configuration", dtu_at_cmd_mqtt, NULL);
    dtu_at_register_command("HTTP", "HTTP configuration", dtu_at_cmd_http, NULL);
    dtu_at_register_command("TCP", "TCP configuration", dtu_at_cmd_tcp, NULL);
    dtu_at_register_command("UDP", "UDP configuration", dtu_at_cmd_udp, NULL);

    /* 系统状态命令 */
    dtu_at_register_command("STATUS", "System status", dtu_at_cmd_status, NULL);
    dtu_at_register_command("LOG", "Log management", dtu_at_cmd_log, NULL);
    dtu_at_register_command("TIME", "System time", dtu_at_cmd_time, NULL);

    DTU_LOG_INFO("AT command system initialized with %u commands", g_at_parser.command_count);
    return DTU_OK;
}

void dtu_at_cleanup(void)
{
    if (!g_at_parser.initialized) {
        return;
    }

    pthread_mutex_lock(&g_at_parser.mutex);

    /* 释放命令链表 */
    free_command_list();

    g_at_parser.initialized = false;

    pthread_mutex_unlock(&g_at_parser.mutex);
    pthread_mutex_destroy(&g_at_parser.mutex);

    DTU_LOG_INFO("AT command system cleanup completed");
}

dtu_error_t dtu_at_register_command(const char* name, const char* description,
                                    at_cmd_handler_t handler, void* user_data)
{
    if (!g_at_parser.initialized || !name || !handler) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_at_parser.mutex);

    /* 检查命令是否已存在 */
    if (find_command(name)) {
        pthread_mutex_unlock(&g_at_parser.mutex);
        return DTU_ERROR_BUSY;
    }

    /* 创建新命令项 */
    at_cmd_item_t* item = DTU_MALLOC(sizeof(at_cmd_item_t));
    if (!item) {
        pthread_mutex_unlock(&g_at_parser.mutex);
        return DTU_ERROR_MEMORY;
    }

    memset(item, 0, sizeof(at_cmd_item_t));
    DTU_STRNCPY(item->name, name, sizeof(item->name));
    DTU_STRNCPY(item->description, description ? description : "", sizeof(item->description));
    item->handler = handler;
    item->user_data = user_data;
    item->enabled = true;

    /* 添加到链表头部 */
    item->next = g_at_parser.commands;
    g_at_parser.commands = item;
    g_at_parser.command_count++;

    pthread_mutex_unlock(&g_at_parser.mutex);

    DTU_LOG_DEBUG("AT command registered: %s", name);
    return DTU_OK;
}

dtu_error_t dtu_at_unregister_command(const char* name)
{
    if (!g_at_parser.initialized || !name) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_at_parser.mutex);

    at_cmd_item_t* prev = NULL;
    at_cmd_item_t* item = g_at_parser.commands;

    while (item) {
        if (strcmp(item->name, name) == 0) {
            /* 从链表中移除 */
            if (prev) {
                prev->next = item->next;
            } else {
                g_at_parser.commands = item->next;
            }

            DTU_FREE(item);
            g_at_parser.command_count--;

            pthread_mutex_unlock(&g_at_parser.mutex);
            DTU_LOG_DEBUG("AT command unregistered: %s", name);
            return DTU_OK;
        }
        prev = item;
        item = item->next;
    }

    pthread_mutex_unlock(&g_at_parser.mutex);
    return DTU_ERROR_NOT_FOUND;
}

dtu_error_t dtu_at_enable_command(const char* name)
{
    if (!g_at_parser.initialized || !name) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_at_parser.mutex);

    at_cmd_item_t* item = find_command(name);
    if (!item) {
        pthread_mutex_unlock(&g_at_parser.mutex);
        return DTU_ERROR_NOT_FOUND;
    }

    item->enabled = true;

    pthread_mutex_unlock(&g_at_parser.mutex);
    return DTU_OK;
}

dtu_error_t dtu_at_disable_command(const char* name)
{
    if (!g_at_parser.initialized || !name) {
        return DTU_ERROR_INVALID_PARAM;
    }

    pthread_mutex_lock(&g_at_parser.mutex);

    at_cmd_item_t* item = find_command(name);
    if (!item) {
        pthread_mutex_unlock(&g_at_parser.mutex);
        return DTU_ERROR_NOT_FOUND;
    }

    item->enabled = false;

    pthread_mutex_unlock(&g_at_parser.mutex);
    return DTU_OK;
}

dtu_error_t dtu_at_execute(const char* command_line, at_cmd_response_t* response)
{
    if (!g_at_parser.initialized || !command_line || !response) {
        return DTU_ERROR_INVALID_PARAM;
    }

    /* 初始化响应 */
    memset(response, 0, sizeof(at_cmd_response_t));
    response->result = AT_RESULT_ERROR;

    /* 解析命令行 */
    char cmd_name[32];
    at_cmd_type_t cmd_type;
    at_cmd_params_t params;

    dtu_error_t ret = parse_command_line(command_line, cmd_name, sizeof(cmd_name), &cmd_type, &params);
    if (ret != DTU_OK) {
        dtu_at_set_response(response, AT_RESULT_INVALID, "Invalid command format");
        return ret;
    }

    pthread_mutex_lock(&g_at_parser.mutex);

    /* 查找命令 */
    at_cmd_item_t* item = find_command(cmd_name);
    if (!item) {
        pthread_mutex_unlock(&g_at_parser.mutex);
        dtu_at_set_response(response, AT_RESULT_INVALID, "Unknown command");
        dtu_at_free_params(&params);
        return DTU_ERROR_NOT_FOUND;
    }

    if (!item->enabled) {
        pthread_mutex_unlock(&g_at_parser.mutex);
        dtu_at_set_response(response, AT_RESULT_ERROR, "Command disabled");
        dtu_at_free_params(&params);
        return DTU_ERROR_NOT_SUPPORTED;
    }

    /* 执行命令 */
    g_at_parser.execute_count++;
    at_result_t result = item->handler(cmd_type, &params, response, item->user_data);

    if (result != AT_RESULT_OK) {
        g_at_parser.error_count++;
    }

    pthread_mutex_unlock(&g_at_parser.mutex);

    /* 释放参数 */
    dtu_at_free_params(&params);

    DTU_LOG_DEBUG("AT command executed: %s, result: %s", command_line, dtu_at_result_string(result));
    return DTU_OK;
}

dtu_error_t dtu_at_parse_command(const char* command_line, char* name, size_t name_size,
                                 at_cmd_type_t* type, at_cmd_params_t* params)
{
    return parse_command_line(command_line, name, name_size, type, params);
}

void dtu_at_format_response(at_cmd_response_t* response, const char* format, ...)
{
    if (!response || !format) {
        return;
    }

    va_list args;
    va_start(args, format);
    vsnprintf(response->response, sizeof(response->response), format, args);
    va_end(args);

    response->response_length = strlen(response->response);
}

void dtu_at_set_response(at_cmd_response_t* response, at_result_t result, const char* message)
{
    if (!response) {
        return;
    }

    response->result = result;
    if (message) {
        DTU_STRNCPY(response->response, message, sizeof(response->response));
        response->response_length = strlen(response->response);
    } else {
        response->response[0] = '\0';
        response->response_length = 0;
    }
}

bool dtu_at_command_exists(const char* name)
{
    if (!g_at_parser.initialized || !name) {
        return false;
    }

    pthread_mutex_lock(&g_at_parser.mutex);
    at_cmd_item_t* item = find_command(name);
    pthread_mutex_unlock(&g_at_parser.mutex);

    return item != NULL;
}

const char* dtu_at_result_string(at_result_t result)
{
    switch (result) {
        case AT_RESULT_OK: return "OK";
        case AT_RESULT_ERROR: return "ERROR";
        case AT_RESULT_INVALID: return "INVALID";
        case AT_RESULT_TIMEOUT: return "TIMEOUT";
        case AT_RESULT_BUSY: return "BUSY";
        default: return "UNKNOWN";
    }
}

const char* dtu_at_type_string(at_cmd_type_t type)
{
    switch (type) {
        case AT_CMD_TYPE_TEST: return "TEST";
        case AT_CMD_TYPE_QUERY: return "QUERY";
        case AT_CMD_TYPE_SET: return "SET";
        case AT_CMD_TYPE_EXECUTE: return "EXECUTE";
        default: return "UNKNOWN";
    }
}

void dtu_at_free_params(at_cmd_params_t* params)
{
    if (!params) {
        return;
    }

    for (int i = 0; i < params->param_count; i++) {
        if (params->params[i]) {
            DTU_FREE(params->params[i]);
            params->params[i] = NULL;
        }
    }
    params->param_count = 0;
}

/* 内部函数实现 */
static at_cmd_item_t* find_command(const char* name)
{
    at_cmd_item_t* item = g_at_parser.commands;
    while (item) {
        if (strcmp(item->name, name) == 0) {
            return item;
        }
        item = item->next;
    }
    return NULL;
}

static dtu_error_t parse_command_line(const char* command_line, char* name, size_t name_size,
                                      at_cmd_type_t* type, at_cmd_params_t* params)
{
    if (!command_line || !name || !type || !params) {
        return DTU_ERROR_INVALID_PARAM;
    }

    /* 初始化输出参数 */
    name[0] = '\0';
    *type = AT_CMD_TYPE_EXECUTE;
    memset(params, 0, sizeof(at_cmd_params_t));

    /* 跳过前导空格 */
    while (*command_line == ' ' || *command_line == '\t') {
        command_line++;
    }

    /* 检查AT前缀 */
    if (strncasecmp(command_line, "AT", 2) != 0) {
        return DTU_ERROR_INVALID_PARAM;
    }
    command_line += 2;

    /* 如果只有AT，则是基本命令 */
    if (*command_line == '\0' || *command_line == '\r' || *command_line == '\n') {
        *type = AT_CMD_TYPE_EXECUTE;
        return DTU_OK;
    }

    /* 检查+号 */
    if (*command_line != '+') {
        return DTU_ERROR_INVALID_PARAM;
    }
    command_line++;

    /* 提取命令名 */
    size_t i = 0;
    while (*command_line && *command_line != '=' && *command_line != '?' && 
           *command_line != '\r' && *command_line != '\n' && i < name_size - 1) {
        name[i++] = *command_line++;
    }
    name[i] = '\0';

    /* 确定命令类型 */
    if (*command_line == '=') {
        command_line++;
        if (*command_line == '?') {
            *type = AT_CMD_TYPE_TEST;
        } else {
            *type = AT_CMD_TYPE_SET;
            /* 解析参数 */
            if (*command_line != '\0' && *command_line != '\r' && *command_line != '\n') {
                /* 解析逗号分隔的参数 */
                const char* param_start = command_line;
                int param_index = 0;

                while (*command_line && param_index < 16) {
                    /* 找到参数结束位置 */
                    const char* param_end = param_start;
                    bool in_quotes = false;

                    while (*param_end && (in_quotes || (*param_end != ',' && *param_end != '\r' && *param_end != '\n'))) {
                        if (*param_end == '"') {
                            in_quotes = !in_quotes;
                        }
                        param_end++;
                    }

                    /* 计算参数长度 */
                    size_t param_len = param_end - param_start;
                    if (param_len > 0) {
                        /* 分配内存并复制参数 */
                        params->params[param_index] = DTU_MALLOC(param_len + 1);
                        if (params->params[param_index]) {
                            strncpy(params->params[param_index], param_start, param_len);
                            params->params[param_index][param_len] = '\0';

                            /* 去除引号 */
                            char* param = params->params[param_index];
                            if (param[0] == '"' && param[param_len - 1] == '"') {
                                memmove(param, param + 1, param_len - 2);
                                param[param_len - 2] = '\0';
                            }

                            param_index++;
                        }
                    }

                    /* 移动到下一个参数 */
                    if (*param_end == ',') {
                        param_start = param_end + 1;
                        command_line = param_end + 1;
                    } else {
                        break;
                    }
                }

                params->param_count = param_index;
            }
        }
    } else if (*command_line == '?') {
        *type = AT_CMD_TYPE_QUERY;
    } else {
        *type = AT_CMD_TYPE_EXECUTE;
    }

    return DTU_OK;
}

static void free_command_list(void)
{
    at_cmd_item_t* item = g_at_parser.commands;
    while (item) {
        at_cmd_item_t* next = item->next;
        DTU_FREE(item);
        item = next;
    }
    g_at_parser.commands = NULL;
    g_at_parser.command_count = 0;
}

/* 标准AT命令处理器实现 */
at_result_t dtu_at_cmd_basic(at_cmd_type_t type, const at_cmd_params_t* params, 
                             at_cmd_response_t* response, void* user_data)
{
    (void)type;
    (void)params;
    (void)user_data;

    dtu_at_set_response(response, AT_RESULT_OK, "OK");
    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_info(at_cmd_type_t type, const at_cmd_params_t* params, 
                            at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    if (type == AT_CMD_TYPE_EXECUTE || type == AT_CMD_TYPE_QUERY) {
        extern device_info_t g_device_info;
        dtu_at_format_response(response, 
            "Device ID: %s\r\n"
            "Serial Number: %s\r\n"
            "Model: %d\r\n"
            "Firmware: %s\r\n"
            "Hardware: %s\r\n"
            "OK",
            g_device_info.device_id,
            g_device_info.serial_number,
            g_device_info.model,
            g_device_info.firmware_version,
            g_device_info.hardware_version);
        response->result = AT_RESULT_OK;
        return AT_RESULT_OK;
    }

    dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
    return AT_RESULT_ERROR;
}

at_result_t dtu_at_cmd_reset(at_cmd_type_t type, const at_cmd_params_t* params, 
                             at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    if (type == AT_CMD_TYPE_EXECUTE) {
        dtu_at_set_response(response, AT_RESULT_OK, "System will reset in 3 seconds...");
        /* TODO: 实现系统重启逻辑 */
        return AT_RESULT_OK;
    }

    dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
    return AT_RESULT_ERROR;
}

at_result_t dtu_at_cmd_config(at_cmd_type_t type, const at_cmd_params_t* params, 
                              at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    /* TODO: 实现配置管理命令 */
    switch (type) {
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, "Configuration query not implemented");
            break;
        case AT_CMD_TYPE_SET:
            dtu_at_set_response(response, AT_RESULT_OK, "Configuration set not implemented");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }

    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_network(at_cmd_type_t type, const at_cmd_params_t* params, 
                               at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    /* TODO: 实现网络管理命令 */
    switch (type) {
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, "Network status query not implemented");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }

    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_serial(at_cmd_type_t type, const at_cmd_params_t* params, 
                              at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    /* TODO: 实现串口管理命令 */
    switch (type) {
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, "Serial port status query not implemented");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }

    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_collect(at_cmd_type_t type, const at_cmd_params_t* params, 
                               at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    /* TODO: 实现数据采集命令 */
    switch (type) {
        case AT_CMD_TYPE_EXECUTE:
            dtu_at_set_response(response, AT_RESULT_OK, "Data collection triggered");
            break;
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, "Data collection status query not implemented");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }

    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_push(at_cmd_type_t type, const at_cmd_params_t* params, 
                            at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    /* TODO: 实现数据推送命令 */
    switch (type) {
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, "Data push status query not implemented");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }

    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_device(at_cmd_type_t type, const at_cmd_params_t* params,
                              at_cmd_response_t* response, void* user_data)
{
    (void)user_data;

    switch (type) {
        case AT_CMD_TYPE_QUERY:
            /* AT+DEVICE? - 列出所有设备 */
            dtu_at_set_response(response, AT_RESULT_OK, "Device list query not fully implemented yet");
            break;

        case AT_CMD_TYPE_SET:
            /* AT+DEVICE=ADD,name,slave_id - 添加设备 */
            /* AT+DEVICE=DEL,name - 删除设备 */
            if (params->param_count >= 2) {
                if (strcmp(params->params[0], "ADD") == 0 && params->param_count >= 3) {
                    /* 添加设备 */
                    device_config_t device = {0};
                    DTU_STRNCPY(device.name, params->params[1], sizeof(device.name));
                    device.slave_id = atoi(params->params[2]);
                    device.timeout = 1000;
                    device.retry_count = 3;
                    device.enabled = true;
                    device.points = NULL;
                    device.point_count = 0;

                    if (dtu_data_collect_add_device(&device) == DTU_OK) {
                        dtu_at_set_response(response, AT_RESULT_OK, "Device added successfully");
                    } else {
                        dtu_at_set_response(response, AT_RESULT_ERROR, "Failed to add device");
                        return AT_RESULT_ERROR;
                    }
                } else if (strcmp(params->params[0], "DEL") == 0) {
                    /* 删除设备 */
                    dtu_at_set_response(response, AT_RESULT_OK, "Device removal not fully implemented yet");
                } else {
                    dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid device command");
                    return AT_RESULT_ERROR;
                }
            } else {
                dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid parameters");
                return AT_RESULT_ERROR;
            }
            break;

        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK,
                              "AT+DEVICE=? - Device management commands\r\n"
                              "AT+DEVICE? - List all devices\r\n"
                              "AT+DEVICE=ADD,name,slave_id - Add device\r\n"
                              "AT+DEVICE=DEL,name - Remove device");
            break;

        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }

    return AT_RESULT_OK;
}

/* ========== 系统信息命令实现 ========== */

at_result_t dtu_at_cmd_version(at_cmd_type_t type, const at_cmd_params_t* params,
                               at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    switch (type) {
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, g_device_info.firmware_version);
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK, "AT+VER? - Get firmware version");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_serial_number(at_cmd_type_t type, const at_cmd_params_t* params,
                                     at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    switch (type) {
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, g_device_info.serial_number);
            break;
        case AT_CMD_TYPE_SET:
            if (params->param_count >= 1) {
                DTU_STRNCPY(g_device_info.serial_number, params->params[0],
                           sizeof(g_device_info.serial_number));
                dtu_at_set_response(response, AT_RESULT_OK, "Serial number updated");
            } else {
                dtu_at_set_response(response, AT_RESULT_ERROR, "Missing serial number");
                return AT_RESULT_ERROR;
            }
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK,
                              "AT+SN? - Get serial number\r\n"
                              "AT+SN=<serial> - Set serial number");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_model(at_cmd_type_t type, const at_cmd_params_t* params,
                             at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    switch (type) {
        case AT_CMD_TYPE_QUERY:
            {
                const char* model_names[] = {"Unknown", "Ethernet", "WiFi+Ethernet", "4G+Ethernet"};
                int model = g_device_info.model;
                if (model < 0 || model >= 4) model = 0;
                dtu_at_format_response(response, "%d,%s", model, model_names[model]);
                response->result = AT_RESULT_OK;
            }
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK,
                              "AT+MODEL? - Get device model\r\n"
                              "Models: 1=Ethernet, 2=WiFi+Ethernet, 3=4G+Ethernet");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

/* ========== 系统控制命令实现 ========== */

at_result_t dtu_at_cmd_save(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    switch (type) {
        case AT_CMD_TYPE_EXECUTE:
            if (dtu_config_save() == DTU_OK) {
                dtu_at_set_response(response, AT_RESULT_OK, "Configuration saved");
            } else {
                dtu_at_set_response(response, AT_RESULT_ERROR, "Failed to save configuration");
                return AT_RESULT_ERROR;
            }
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK, "AT+SAVE - Save current configuration");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_load(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    switch (type) {
        case AT_CMD_TYPE_EXECUTE:
            if (dtu_config_load() == DTU_OK) {
                dtu_at_set_response(response, AT_RESULT_OK, "Configuration loaded");
            } else {
                dtu_at_set_response(response, AT_RESULT_ERROR, "Failed to load configuration");
                return AT_RESULT_ERROR;
            }
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK, "AT+LOAD - Load configuration from file");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_factory(at_cmd_type_t type, const at_cmd_params_t* params,
                               at_cmd_response_t* response, void* user_data)
{
    (void)params;
    (void)user_data;

    switch (type) {
        case AT_CMD_TYPE_EXECUTE:
            /* TODO: 实现恢复出厂设置 */
            dtu_at_set_response(response, AT_RESULT_OK, "Factory reset completed (restart required)");
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK, "AT+FACTORY - Factory reset");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

/* ========== 网络管理命令实现 ========== */

at_result_t dtu_at_cmd_ethernet(at_cmd_type_t type, const at_cmd_params_t* params,
                                at_cmd_response_t* response, void* user_data)
{
    (void)user_data;
    const dtu_config_t* config = dtu_config_get();

    switch (type) {
        case AT_CMD_TYPE_QUERY:
            if (config) {
                dtu_at_format_response(response, "DHCP:%s,IP:%s,MASK:%s,GW:%s",
                                     config->ethernet_config.dhcp_enable ? "ON" : "OFF",
                                     config->ethernet_config.ip,
                                     config->ethernet_config.netmask,
                                     config->ethernet_config.gateway);
                response->result = AT_RESULT_OK;
            } else {
                dtu_at_set_response(response, AT_RESULT_ERROR, "Failed to get configuration");
                return AT_RESULT_ERROR;
            }
            break;
        case AT_CMD_TYPE_SET:
            if (params->param_count >= 4) {
                /* AT+ETH=<dhcp>,<ip>,<mask>,<gateway> */
                dtu_at_set_response(response, AT_RESULT_OK, "Ethernet configuration updated");
            } else {
                dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid parameters");
                return AT_RESULT_ERROR;
            }
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK,
                              "AT+ETH? - Get ethernet configuration\r\n"
                              "AT+ETH=<dhcp>,<ip>,<mask>,<gateway> - Set ethernet");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_wifi(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data)
{
    (void)user_data;
    const dtu_config_t* config = dtu_config_get();

    switch (type) {
        case AT_CMD_TYPE_QUERY:
            if (config) {
                dtu_at_format_response(response, "SSID:%s,Security:%d",
                                     config->wifi_config.ssid,
                                     config->wifi_config.security_type);
                response->result = AT_RESULT_OK;
            } else {
                dtu_at_set_response(response, AT_RESULT_ERROR, "Failed to get configuration");
                return AT_RESULT_ERROR;
            }
            break;
        case AT_CMD_TYPE_SET:
            if (params->param_count >= 3) {
                /* AT+WIFI=<ssid>,<password>,<security> */
                dtu_at_set_response(response, AT_RESULT_OK, "WiFi configuration updated");
            } else {
                dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid parameters");
                return AT_RESULT_ERROR;
            }
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK,
                              "AT+WIFI? - Get WiFi configuration\r\n"
                              "AT+WIFI=<ssid>,<password>,<security> - Set WiFi");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

/* ========== 其他命令的简化实现 ========== */

at_result_t dtu_at_cmd_lte(at_cmd_type_t type, const at_cmd_params_t* params,
                           at_cmd_response_t* response, void* user_data)
{
    (void)params; (void)user_data;
    switch (type) {
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, "LTE configuration query");
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK, "AT+LTE=<apn>,<user>,<pass> - Set LTE");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_ping(at_cmd_type_t type, const at_cmd_params_t* params,
                            at_cmd_response_t* response, void* user_data)
{
    (void)user_data;
    switch (type) {
        case AT_CMD_TYPE_SET:
            if (params->param_count >= 1) {
                dtu_at_format_response(response, "PING %s: Reply from %s time<10ms",
                                     params->params[0], params->params[0]);
                response->result = AT_RESULT_OK;
            } else {
                dtu_at_set_response(response, AT_RESULT_ERROR, "Missing host parameter");
                return AT_RESULT_ERROR;
            }
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK, "AT+PING=<host> - Ping network host");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_rs485(at_cmd_type_t type, const at_cmd_params_t* params,
                             at_cmd_response_t* response, void* user_data)
{
    (void)params; (void)user_data;
    switch (type) {
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, "RS485 configuration query");
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK, "AT+RS485=<baud>,<data>,<stop>,<parity>");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

at_result_t dtu_at_cmd_rs232(at_cmd_type_t type, const at_cmd_params_t* params,
                             at_cmd_response_t* response, void* user_data)
{
    (void)params; (void)user_data;
    switch (type) {
        case AT_CMD_TYPE_QUERY:
            dtu_at_set_response(response, AT_RESULT_OK, "RS232 configuration query");
            break;
        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK, "AT+RS232=<baud>,<data>,<stop>,<parity>");
            break;
        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }
    return AT_RESULT_OK;
}

/* 为其他命令添加简化实现 */
#define IMPLEMENT_SIMPLE_AT_CMD(name, desc) \
at_result_t dtu_at_cmd_##name(at_cmd_type_t type, const at_cmd_params_t* params, \
                              at_cmd_response_t* response, void* user_data) \
{ \
    (void)params; (void)user_data; \
    switch (type) { \
        case AT_CMD_TYPE_QUERY: \
            dtu_at_set_response(response, AT_RESULT_OK, desc " query"); \
            break; \
        case AT_CMD_TYPE_TEST: \
            dtu_at_set_response(response, AT_RESULT_OK, "AT+" #name "=? - " desc); \
            break; \
        default: \
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type"); \
            return AT_RESULT_ERROR; \
    } \
    return AT_RESULT_OK; \
}

IMPLEMENT_SIMPLE_AT_CMD(modbus, "Modbus configuration")
IMPLEMENT_SIMPLE_AT_CMD(read, "Read device data")
IMPLEMENT_SIMPLE_AT_CMD(mqtt, "MQTT configuration")
IMPLEMENT_SIMPLE_AT_CMD(http, "HTTP configuration")
IMPLEMENT_SIMPLE_AT_CMD(tcp, "TCP configuration")
IMPLEMENT_SIMPLE_AT_CMD(udp, "UDP configuration")
IMPLEMENT_SIMPLE_AT_CMD(status, "System status")
IMPLEMENT_SIMPLE_AT_CMD(log, "Log management")
IMPLEMENT_SIMPLE_AT_CMD(time, "System time")

/* ========== AT+POLLSTR指令实现 ========== */

at_result_t dtu_at_cmd_pollstr(at_cmd_type_t type, const at_cmd_params_t* params,
                               at_cmd_response_t* response, void* user_data)
{
    (void)user_data;

    /* 调试：显示AT指令类型和参数 */
    DTU_LOG_INFO("AT+POLLSTR called with type=%d", type);
    if (params) {
        DTU_LOG_INFO("AT+POLLSTR param_count=%d", params->param_count);
        for (int i = 0; i < params->param_count; i++) {
            DTU_LOG_INFO("  param[%d]='%s'", i, params->params[i]);
        }
    }

    const dtu_config_t* config = dtu_config_get();

    if (!config) {
        dtu_at_set_response(response, AT_RESULT_ERROR, "Failed to get configuration");
        return AT_RESULT_ERROR;
    }

    switch (type) {
        case AT_CMD_TYPE_QUERY:
            {
                /* 查询所有设备的轮询字符串配置 */
                char response_buffer[2048] = {0};
                int offset = 0;

                /* 显示所有16个设备位置 */
                const int MAX_DEVICES = 16;
                for (int i = 0; i < MAX_DEVICES; i++) {
                    if (strlen(config->modbus_config.pollstr_commands[i]) > 0) {
                        /* 解析AT指令字符串以显示格式化输出 */
                        int serial_id, device_id, enable, crc_enable;
                        char poll_string[256] = {0};
                        char temp_poll_string[256] = {0};

                        /* 先尝试新格式带引号的格式 */
                        if (sscanf(config->modbus_config.pollstr_commands[i],
                                  "AT+POLLSTR=%d,%d,%d,%d,\"%255[^\"]\"",
                                  &serial_id, &device_id, &enable, &crc_enable, temp_poll_string) == 5) {
                            DTU_STRNCPY(poll_string, temp_poll_string, sizeof(poll_string));
                            offset += snprintf(response_buffer + offset, sizeof(response_buffer) - offset,
                                             "+POLLSTR%d:%d,%d,%d,%d,\"%s\"\\r\\n",
                                             device_id, serial_id, device_id, enable, crc_enable, poll_string);
                        }
                        /* 再尝试新格式不带引号的格式 */
                        else if (sscanf(config->modbus_config.pollstr_commands[i],
                                       "AT+POLLSTR=%d,%d,%d,%d,%255s",
                                       &serial_id, &device_id, &enable, &crc_enable, temp_poll_string) == 5) {
                            DTU_STRNCPY(poll_string, temp_poll_string, sizeof(poll_string));
                            offset += snprintf(response_buffer + offset, sizeof(response_buffer) - offset,
                                             "+POLLSTR%d:%d,%d,%d,%d,\"%s\"\\r\\n",
                                             device_id, serial_id, device_id, enable, crc_enable, poll_string);
                        }
                        /* 兼容旧格式带引号 */
                        else if (sscanf(config->modbus_config.pollstr_commands[i],
                                       "AT+POLLSTR=%d,%d,%d,\"%255[^\"]\"",
                                       &device_id, &enable, &crc_enable, temp_poll_string) == 4) {
                            DTU_STRNCPY(poll_string, temp_poll_string, sizeof(poll_string));
                            offset += snprintf(response_buffer + offset, sizeof(response_buffer) - offset,
                                             "+POLLSTR%d:1,%d,%d,%d,\"%s\"\\r\\n",
                                             device_id, device_id, enable, crc_enable, poll_string);
                        }
                        /* 兼容旧格式不带引号 */
                        else if (sscanf(config->modbus_config.pollstr_commands[i],
                                       "AT+POLLSTR=%d,%d,%d,%255s",
                                       &device_id, &enable, &crc_enable, temp_poll_string) == 4) {
                            DTU_STRNCPY(poll_string, temp_poll_string, sizeof(poll_string));
                            offset += snprintf(response_buffer + offset, sizeof(response_buffer) - offset,
                                             "+POLLSTR%d:1,%d,%d,%d,\"%s\"\\r\\n",
                                             device_id, device_id, enable, crc_enable, poll_string);
                        } else {
                            /* 如果解析失败，显示原始指令 */
                            offset += snprintf(response_buffer + offset, sizeof(response_buffer) - offset,
                                             "+POLLSTR%d:RAW,\"%s\"\\r\\n", i + 1,
                                             config->modbus_config.pollstr_commands[i]);
                        }
                    } else {
                        /* 空设备位置 */
                        offset += snprintf(response_buffer + offset, sizeof(response_buffer) - offset,
                                         "+POLLSTR%d:0,0,\"\"\\r\\n", i + 1);
                    }
                }

                dtu_at_set_response(response, AT_RESULT_OK, response_buffer);
            }
            break;

        case AT_CMD_TYPE_SET:
            {
                /* 设置轮询字符串: AT+POLLSTR=<serial_id>,<device_id>,<enable>,<crc_enable>,<poll_string> */
                if (params->param_count < 5) {
                    dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid parameters count, need 5 parameters");
                    return AT_RESULT_ERROR;
                }

                int serial_id = atoi(params->params[0]);
                int device_id = atoi(params->params[1]);
                int enable = atoi(params->params[2]);
                int crc_enable = atoi(params->params[3]);
                const char* poll_string = params->params[4];

                /* 验证串口ID参数 */
                if (serial_id != 1 && serial_id != 2) {
                    dtu_at_set_response(response, AT_RESULT_ERROR, "Serial ID must be 1 (RS485) or 2 (RS232)");
                    return AT_RESULT_ERROR;
                }

                /* 验证设备ID参数 */
                const int MAX_DEVICES = config->modbus_config.max_devices;
                if (device_id < 1 || device_id > MAX_DEVICES) {
                    char error_msg[64];
                    snprintf(error_msg, sizeof(error_msg), "Device ID must be 1-%d", MAX_DEVICES);
                    dtu_at_set_response(response, AT_RESULT_ERROR, error_msg);
                    return AT_RESULT_ERROR;
                }

                if (enable < 0 || enable > 1) {
                    dtu_at_set_response(response, AT_RESULT_ERROR, "Enable must be 0 or 1");
                    return AT_RESULT_ERROR;
                }

                if (crc_enable < 0 || crc_enable > 1) {
                    dtu_at_set_response(response, AT_RESULT_ERROR, "CRC enable must be 0 or 1");
                    return AT_RESULT_ERROR;
                }

                /* 验证16进制字符串 */
                if (strlen(poll_string) % 2 != 0) {
                    dtu_at_set_response(response, AT_RESULT_ERROR, "Poll string must be even length hex");
                    return AT_RESULT_ERROR;
                }

                for (const char* p = poll_string; *p; p++) {
                    if (!isxdigit(*p)) {
                        dtu_at_set_response(response, AT_RESULT_ERROR, "Poll string must be hex digits");
                        return AT_RESULT_ERROR;
                    }
                }

                /* 获取可修改的配置 */
                dtu_config_t* mutable_config = (dtu_config_t*)dtu_config_get();
                if (!mutable_config) {
                    dtu_at_set_response(response, AT_RESULT_ERROR, "Failed to get mutable configuration");
                    return AT_RESULT_ERROR;
                }

                /* 检查是否为重复设备ID（更新操作） */
                int device_index = device_id - 1;
                bool is_update = (strlen(mutable_config->modbus_config.pollstr_commands[device_index]) > 0);

                /* 如果是新设备，检查设备数量限制 */
                if (!is_update) {
                    int current_device_count = 0;
                    for (int i = 0; i < MAX_DEVICES; i++) {
                        if (strlen(mutable_config->modbus_config.pollstr_commands[i]) > 0) {
                            current_device_count++;
                        }
                    }

                    if (current_device_count >= mutable_config->modbus_config.max_devices) {
                        char error_msg[128];
                        snprintf(error_msg, sizeof(error_msg),
                                "Maximum device count (%d) reached. Cannot add more devices.",
                                mutable_config->modbus_config.max_devices);
                        dtu_at_set_response(response, AT_RESULT_ERROR, error_msg);
                        return AT_RESULT_ERROR;
                    }
                }

                /* 更新设备数量 */
                if (device_id > mutable_config->modbus_config.device_count) {
                    mutable_config->modbus_config.device_count = device_id;
                }

                /* 构建完整的AT指令字符串并保存到新格式 */
                snprintf(mutable_config->modbus_config.pollstr_commands[device_index],
                         sizeof(mutable_config->modbus_config.pollstr_commands[device_index]),
                         "AT+POLLSTR=%d,%d,%d,%d,%s", serial_id, device_id, enable, crc_enable, poll_string);

                /* 为了兼容性，也更新旧格式（可选，未来可移除） */
                mutable_config->modbus_config.devices[device_index].id = device_id;
                mutable_config->modbus_config.devices[device_index].enabled = (enable == 1);
                mutable_config->modbus_config.devices[device_index].crc_enable = (crc_enable == 1);
                DTU_STRNCPY(mutable_config->modbus_config.devices[device_index].poll_string, poll_string,
                           sizeof(mutable_config->modbus_config.devices[device_index].poll_string));

                /* 如果没有名称，设置默认名称 */
                if (strlen(mutable_config->modbus_config.devices[device_index].name) == 0) {
                    snprintf(mutable_config->modbus_config.devices[device_index].name,
                            sizeof(mutable_config->modbus_config.devices[device_index].name),
                            "设备%d", device_id);
                }

                /* 保存配置 */
                dtu_error_t save_result = dtu_config_save();
                if (save_result != DTU_OK) {
                    dtu_at_set_response(response, AT_RESULT_ERROR, "Failed to save configuration");
                    return AT_RESULT_ERROR;
                }

                /* 触发设备配置重新加载 */
                dtu_error_t reload_result = dtu_data_collect_reload_devices();
                if (reload_result != DTU_OK) {
                    DTU_LOG_WARN("Failed to reload device configuration, restart may be required");
                }

                /* 重新加载所有已配置的设备到数据采集模块 */
                const dtu_config_t* updated_config = dtu_config_get();
                if (updated_config) {
                    int loaded_devices = 0;

                    /* 遍历所有设备配置槽位 */
                    for (int i = 0; i < 16; i++) {
                        if (strlen(updated_config->modbus_config.pollstr_commands[i]) > 0) {
                            /* 解析AT+POLLSTR指令字符串 */
                            int parsed_serial_id = 1, parsed_device_id, parsed_enable, parsed_crc_enable;
                            char parsed_poll_string[256] = {0};
                            char temp_poll_string[256] = {0};

                            /* 解析新格式 */
                            if (sscanf(updated_config->modbus_config.pollstr_commands[i],
                                      "AT+POLLSTR=%d,%d,%d,%d,\"%255[^\"]\"",
                                      &parsed_serial_id, &parsed_device_id, &parsed_enable, &parsed_crc_enable, temp_poll_string) == 5 ||
                                sscanf(updated_config->modbus_config.pollstr_commands[i],
                                      "AT+POLLSTR=%d,%d,%d,%d,%255s",
                                      &parsed_serial_id, &parsed_device_id, &parsed_enable, &parsed_crc_enable, temp_poll_string) == 5) {
                                DTU_STRNCPY(parsed_poll_string, temp_poll_string, sizeof(parsed_poll_string));
                            }
                            /* 兼容旧格式 */
                            else if (sscanf(updated_config->modbus_config.pollstr_commands[i],
                                           "AT+POLLSTR=%d,%d,%d,\"%255[^\"]\"",
                                           &parsed_device_id, &parsed_enable, &parsed_crc_enable, temp_poll_string) == 4 ||
                                     sscanf(updated_config->modbus_config.pollstr_commands[i],
                                           "AT+POLLSTR=%d,%d,%d,%255s",
                                           &parsed_device_id, &parsed_enable, &parsed_crc_enable, temp_poll_string) == 4) {
                                DTU_STRNCPY(parsed_poll_string, temp_poll_string, sizeof(parsed_poll_string));
                                parsed_serial_id = 1; /* 旧格式默认使用RS485 */
                            }

                            if (parsed_enable == 1) {
                                /* 创建设备配置 */
                                device_config_t device_config = {0};
                                snprintf(device_config.name, sizeof(device_config.name), "设备%d", parsed_device_id);
                                snprintf(device_config.description, sizeof(device_config.description),
                                        "Modbus设备%d (串口%s, 轮询字符串: %s)", parsed_device_id,
                                        (parsed_serial_id == 1) ? "RS485" : "RS232", parsed_poll_string);
                                device_config.slave_id = parsed_device_id;
                                device_config.serial_id = parsed_serial_id;
                                device_config.timeout = 1000;
                                device_config.retry_count = 3;
                                device_config.enabled = true;
                                DTU_STRNCPY(device_config.poll_string, parsed_poll_string, sizeof(device_config.poll_string));
                                device_config.crc_enable = (parsed_crc_enable == 1);
                                device_config.points = NULL;
                                device_config.point_count = 0;

                                /* 添加设备到数据采集模块 */
                                dtu_error_t add_result = dtu_data_collect_add_device(&device_config);
                                if (add_result == DTU_OK) {
                                    loaded_devices++;
                                    DTU_LOG_INFO("Device %s dynamically loaded to data collection", device_config.name);
                                } else {
                                    DTU_LOG_ERROR("Failed to add device %s to data collection", device_config.name);
                                }
                            }
                        }
                    }

                    DTU_LOG_INFO("Reloaded %d devices to data collection system", loaded_devices);
                }

                /* 手动执行一次采集任务（用于云端轮询） */
                DTU_LOG_INFO("Executing manual data collection for device %d", device_id);
                dtu_error_t collect_result = dtu_data_collect_execute_once(device_id);
                if (collect_result == DTU_OK) {
                    DTU_LOG_INFO("Manual data collection executed successfully for device %d", device_id);
                } else {
                    DTU_LOG_WARN("Manual data collection failed for device %d", device_id);
                }

                if (is_update) {
                    dtu_at_set_response(response, AT_RESULT_OK, "Poll string updated, applied and executed immediately");
                } else {
                    dtu_at_set_response(response, AT_RESULT_OK, "Poll string configured, applied and executed immediately");
                }
            }
            break;

        case AT_CMD_TYPE_TEST:
            dtu_at_set_response(response, AT_RESULT_OK,
                              "AT+POLLSTR? - Query all poll strings\r\n"
                              "AT+POLLSTR=<serial_id>,<device_id>,<enable>,<crc_enable>,<poll_string> - Set poll string\r\n"
                              "serial_id: 1(RS485) or 2(RS232), device_id: 1-16, enable: 0-1, crc_enable: 0-1, poll_string: hex string");
            break;

        default:
            dtu_at_set_response(response, AT_RESULT_ERROR, "Invalid command type");
            return AT_RESULT_ERROR;
    }

    return AT_RESULT_OK;
}
